const Competitor = require('../models/Competitor');
const Site = require('../models/Site');
const ErrorResponse = require('../utils/errorResponse');

// @desc    添加竞争对手
// @route   POST /api/competitors
// @access  Private
const addCompetitor = async (req, res) => {
  try {
    const { domain, siteId } = req.body;
    const userId = req.user.id;

    // 检查网站是否存在
    const site = await Site.findById(siteId);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权为此网站添加竞争对手' 
      });
    }

    // 创建竞争对手记录
    const newCompetitor = await Competitor.create({
      user: userId,
      site: siteId,
      domain
    });

    res.status(201).json({
      status: 'success',
      data: newCompetitor
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    获取用户所有竞争对手
// @route   GET /api/competitors
// @access  Private
const getCompetitors = async (req, res) => {
  try {
    const competitors = await Competitor.find({ user: req.user.id })
      .populate('site', 'name url');
    
    res.status(200).json({
      status: 'success',
      data: competitors
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    分析竞争对手
// @route   GET /api/competitors/:id/analyze
// @access  Private
const analyzeCompetitor = async (req, res) => {
  try {
    const { id } = req.params;

    const competitor = await Competitor.findById(id);
    if (!competitor) {
      return res.status(404).json({ 
        status: 'error', 
        message: '竞争对手不存在' 
      });
    }

    // 确保用户拥有该竞争对手
    if (competitor.user.toString() !== req.user.id) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权分析此竞争对手' 
      });
    }

    // 模拟竞争对手分析结果
    const analysisResult = {
      ...competitor.toObject(),
      topKeywords: generateTopKeywords(10),
      backlinkSources: generateBacklinkSources(5),
      contentAnalysis: generateContentAnalysis(),
      trafficSources: generateTrafficSources(),
      timestamp: new Date()
    };

    // 保存分析结果
    competitor.analysisHistory.push({
      data: analysisResult
    });
    await competitor.save();

    res.status(200).json({
      status: 'success',
      data: analysisResult
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    与竞争对手比较
// @route   POST /api/competitors/compare
// @access  Private
const compareWithCompetitor = async (req, res) => {
  try {
    const { siteId, competitorId } = req.body;
    const userId = req.user.id;

    // 获取我的网站数据
    const mySite = await Site.findById(siteId);
    if (!mySite) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (mySite.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权比较此网站' 
      });
    }

    // 获取竞争对手数据
    const competitor = await Competitor.findById(competitorId);
    if (!competitor) {
      return res.status(404).json({ 
        status: 'error', 
        message: '竞争对手不存在' 
      });
    }

    // 确保用户拥有该竞争对手
    if (competitor.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权比较此竞争对手' 
      });
    }

    // 模拟比较结果
    const comparisonResult = {
      mySite: {
        domainAuthority: mySite.stats.domainAuthority,
        backlinks: mySite.stats.backlinks,
        organicTraffic: mySite.stats.organicTraffic,
        rankingKeywords: mySite.stats.rankingKeywords
      },
      competitor: {
        domainAuthority: competitor.stats.domainAuthority,
        backlinks: competitor.stats.backlinks,
        organicTraffic: competitor.stats.organicTraffic,
        rankingKeywords: competitor.stats.rankingKeywords
      },
      gapAnalysis: {
        backlinkGap: generateBacklinkGapAnalysis(mySite._id, competitor._id),
        keywordGap: generateKeywordGapAnalysis(mySite._id, competitor._id),
        contentGap: generateContentGapAnalysis(mySite._id, competitor._id)
      },
      timestamp: new Date()
    };

    res.status(200).json({
      status: 'success',
      data: comparisonResult
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    追踪竞争对手关键词
// @route   POST /api/competitors/track-keywords
// @access  Private
const trackCompetitorKeywords = async (req, res) => {
  try {
    const { competitorId, keywords } = req.body;
    const userId = req.user.id;

    const competitor = await Competitor.findById(competitorId);
    if (!competitor) {
      return res.status(404).json({ 
        status: 'error', 
        message: '竞争对手不存在' 
      });
    }

    // 确保用户拥有该竞争对手
    if (competitor.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权追踪此竞争对手的关键词' 
      });
    }

    // 模拟关键词追踪结果
    const trackingResult = keywords.map(keyword => ({
      keyword,
      competitorRank: Math.floor(Math.random() * 10) + 1,
      myRank: Math.floor(Math.random() * 100),
      competitorUrl: `https://${competitor.domain}/${keyword.replace(/\s+/g, '-')}`,
      searchVolume: Math.floor(Math.random() * 10000),
      difficulty: Math.floor(Math.random() * 100)
    }));

    // 保存追踪结果
    competitor.trackingKeywords = trackingResult;
    await competitor.save();

    res.status(200).json({
      status: 'success',
      data: trackingResult
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// 生成竞争对手热门关键词的辅助函数
const generateTopKeywords = (count) => {
  const keywords = [];
  const sampleKeywords = [
    'seo tools', 'website optimization', 'google ranking',
    'keyword research', 'backlink analysis', 'content marketing',
    'on-page seo', 'technical seo', 'local seo', 'ecommerce seo'
  ];
  
  for (let i = 0; i < count; i++) {
    keywords.push({
      keyword: sampleKeywords[Math.floor(Math.random() * sampleKeywords.length)],
      rank: Math.floor(Math.random() * 10) + 1,
      traffic: Math.floor(Math.random() * 10000),
      cpc: (Math.random() * 10).toFixed(2)
    });
  }
  
  return keywords;
};

// 生成反向链接来源的辅助函数
const generateBacklinkSources = (count) => {
  const sources = [];
  const domains = [
    'forbes.com', 'wikipedia.org', 'nytimes.com',
    'techcrunch.com', 'mashable.com', 'reddit.com',
    'quora.com', 'medium.com', 'github.com', 'wordpress.org'
  ];
  
  for (let i = 0; i < count; i++) {
    sources.push({
      domain: domains[Math.floor(Math.random() * domains.length)],
      backlinks: Math.floor(Math.random() * 100) + 1,
      domainAuthority: Math.floor(Math.random() * 100),
      lastSeen: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000)
    });
  }
  
  return sources;
};

// 生成内容分析的辅助函数
const generateContentAnalysis = () => {
  return {
    totalPages: Math.floor(Math.random() * 10000),
    blogPosts: Math.floor(Math.random() * 1000),
    avgWordCount: Math.floor(Math.random() * 2000) + 500,
    contentUpdateFrequency: `${Math.floor(Math.random() * 30) + 1}天`,
    topContentTypes: [
      { type: '博客文章', percentage: Math.floor(Math.random() * 50) + 30 },
      { type: '产品页面', percentage: Math.floor(Math.random() * 30) + 10 },
      { type: '指南/教程', percentage: Math.floor(Math.random() * 20) + 5 }
    ]
  };
};

// 生成流量来源的辅助函数
const generateTrafficSources = () => {
  return {
    organic: Math.floor(Math.random() * 70) + 20,
    direct: Math.floor(Math.random() * 20) + 5,
    referral: Math.floor(Math.random() * 15) + 5,
    social: Math.floor(Math.random() * 10) + 1,
    paid: Math.floor(Math.random() * 5)
  };
};

// 生成反向链接差距分析的辅助函数
const generateBacklinkGapAnalysis = (mySiteId, competitorId) => {
  return {
    uniqueToCompetitor: Math.floor(Math.random() * 1000),
    uniqueToMe: Math.floor(Math.random() * 100),
    overlapping: Math.floor(Math.random() * 500),
    topOpportunities: generateBacklinkSources(5)
  };
};

// 生成关键词差距分析的辅助函数
const generateKeywordGapAnalysis = (mySiteId, competitorId) => {
  return {
    uniqueToCompetitor: Math.floor(Math.random() * 5000),
    uniqueToMe: Math.floor(Math.random() * 1000),
    overlapping: Math.floor(Math.random() * 2000),
    topOpportunities: generateTopKeywords(10)
  };
};

// 生成内容差距分析的辅助函数
const generateContentGapAnalysis = (mySiteId, competitorId) => {
  const topics = [
    'SEO技巧', '内容营销', '网站优化',
    '关键词研究', '技术SEO', '本地SEO',
    '电子商务SEO', '移动端优化', '用户体验'
  ];
  
  return topics.slice(0, 5).map(topic => ({
    topic,
    competitorCoverage: Math.random() > 0.3,
    myCoverage: Math.random() > 0.2,
    opportunityScore: Math.floor(Math.random() * 100)
  }));
};

module.exports = {
  addCompetitor,
  getCompetitors,
  analyzeCompetitor,
  compareWithCompetitor,
  trackCompetitorKeywords
};